// 检查是否为转发动态
function isRepostDynamic(item) {
  const forwardDesc = item.querySelector(".bili-dyn-content__forw__desc");
  return forwardDesc?.textContent?.trim().includes("转发动态");
}

let Stop = false;
async function processDynamicItems() {
  // 获取动态列表容器
  const itemsContainer = document.querySelector(".bili-dyn-list__items");

  if (!itemsContainer) {
    console.error("动态列表容器未找到");
    return;
  }

  // 开始平滑滚动并处理可见项
  await startContinuousScroll(itemsContainer);

  // 处理更多按钮
  async function processMoreButton(item) {
    const btn = item.querySelector(".bili-dyn-more__btn, .more-btn");
    if (!btn) {
      console.log("未找到更多按钮");
      return;
    }

    console.log("找到更多按钮，模拟交互");

    await simulateHover(btn);
    console.log(btn);
    const deletebtn = btn.querySelectorAll(
      ".bili-cascader-options__item-label"
    )[1];
    console.log(deletebtn);
    await simulateClick(deletebtn);

    await delay(100);

    // 点击动态确定删除
    const confirm = document.querySelector(".bili-modal__button.confirm.red");
    await simulateClick(confirm);
    await delay(200);
  }

  // 模拟hover效果
  async function simulateHover(element) {
    const events = ["mouseover", "mouseenter", "mousemove"];
    for (const eventType of events) {
      element.dispatchEvent(
        new MouseEvent(eventType, {
          bubbles: true,
          cancelable: true,
          view: window,
          clientX: element.getBoundingClientRect().x + 10,
          clientY: element.getBoundingClientRect().y + 10,
        })
      );
      await delay(100);
    }
  }

  // 模拟点击函数
  async function simulateClick(element) {
    element.dispatchEvent(
      new MouseEvent("mousedown", {
        bubbles: true,
        cancelable: true,
        view: window,
      })
    );
    await delay(50);
    element.dispatchEvent(
      new MouseEvent("mouseup", {
        bubbles: true,
        cancelable: true,
        view: window,
      })
    );
    await delay(50);
    element.dispatchEvent(
      new MouseEvent("click", { bubbles: true, cancelable: true, view: window })
    );
  }

  // 启动连续平滑滚动（到底停止）
  async function startContinuousScroll(container) {
    let scrollDirection = 1; // 1=向下
    const scrollStep = 300; // 每次滚动的像素数
    const checkInterval = 300; // 检查间隔(ms)
    let isProcessing = false; // 防止重复处理
    let shouldContinue = true; // 控制是否继续滚动

    while (shouldContinue) {
      // 获取当前视口中的可见项
      const visibleItems = getVisibleItems(container);

      // 处理当前可见项
      if (!isProcessing) {
        isProcessing = true;
        for (const item of visibleItems) {
          if (isRepostDynamic(item)) {
            // 如果是转发动态，模拟hover并处理
            await processMoreButton(item);
          }
        }
        isProcessing = false;
      }

      // 检查是否到达底部
      const nearBottom =
        window.innerHeight + window.pageYOffset >=
        document.body.scrollHeight - 100;

      console.log(Stop);
      if (nearBottom || Stop) {
        console.log("已滚动到页面底部，停止滚动");
        shouldContinue = false; // 停止循环
        break;
      }

      // 执行平滑滚动
      await enhancedSmoothScroll(scrollStep * scrollDirection, checkInterval);

      // 短暂延迟防止过度占用CPU
      await delay(50);
    }

    // 滚动结束后可以执行其他操作
    console.log("滚动已停止");
  }

  // 增强版平滑滚动
  async function enhancedSmoothScroll(amount, duration = 500) {
    return new Promise((resolve) => {
      const startY = window.pageYOffset;
      const startTime = performance.now();

      function scrollStep(timestamp) {
        const elapsed = timestamp - startTime;
        const progress = Math.min(elapsed / duration, 1);
        const easeProgress = easeOutQuad(progress);

        window.scrollTo(0, startY + amount * easeProgress);

        if (progress < 1) {
          requestAnimationFrame(scrollStep);
        } else {
          resolve();
        }
      }

      requestAnimationFrame(scrollStep);
    });
  }

  // 获取当前视口中的可见项
  function getVisibleItems(container) {
    return Array.from(container.children).filter((item) => {
      if (item.nodeType !== Node.ELEMENT_NODE) return false;
      const rect = item.getBoundingClientRect();
      return (
        rect.top < window.innerHeight &&
        rect.bottom > 0 &&
        rect.left < window.innerWidth &&
        rect.right > 0
      );
    });
  }
}

// 缓动函数 - 二次缓出
function easeOutQuad(t) {
  return t * (2 - t);
}

// 延迟函数
function delay(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

function mainDynamic() {
  const dynamic__left = document.querySelector(".side-nav");
  console.log(dynamic__left);
  if (dynamic__left) {
    const delete_btn = document.createElement("div");
    delete_btn.className = "side-nav__item delete_btn";
    delete_btn.textContent = "删除转发动态";
    dynamic__left.appendChild(delete_btn);

    delete_btn.addEventListener("click", function () {
      Stop = false;
      processDynamicItems();
    });

    const stop_btn = document.createElement("div");
    stop_btn.className = "side-nav__item  stop_btn";
    stop_btn.textContent = "停止动态";
    dynamic__left.appendChild(stop_btn);

    stop_btn.addEventListener("click", function () {
      Stop = true;
    });
  } else {
    setTimeout(mainDynamic, 500); // 每500ms检查一次
  }
}
